﻿using System;
using Deer.Time;
using Deer.Timer;

namespace Telex.Timer;

sealed class SingleTimer : ITimerTask
{
    private readonly static TimeSpan interval = TimeSpan.FromSeconds(5);
    
    public readonly static SingleTimer instance = new SingleTimer();

    private SingleTimer()
    {
        TimerRunner.CreateTimeout(this, interval);
    }
    
    void ITimerTask.Run(ITimeout timeout)
    {
        this.OnTimerEvent();
        TimerRunner.CreateTimeout(this, interval);
    }

    private Action<long> funcs;

    public void AddListener(Action<long> func)
    {
        if(func == null)
        {
            return;
        }

        this.funcs += func;
    }

    public void DelListener(Action<long> func)
    {
        if(func == null)
        {
            return;
        }

        this.funcs -= func;
    }

    private void OnTimerEvent()
    {
        if(this.funcs != null)
        {
            this.funcs(TimeUtil.GetTimestamp(DateTime.UtcNow));
        }
    }
}